<template>
  <div class="english-chat-container">
    <Header :url="userImageUrl" />
    <div class="chat-main">
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h3>英语对话</h3>
          <el-button type="primary" size="small" @click="openNewChatDialog" class="new-chat-btn">
            <i class="el-icon-plus"></i> 开始新对话
          </el-button>
        </div>
        <div class="chat-contacts">
          <div 
            v-for="(chat, index) in chats" 
            :key="chat.id" 
            class="contact-item"
            :class="{ 'active': activeContact === chat.id }"
            @click="selectContact(chat.id)"
          >
            <div class="contact-main">
              <el-avatar :src="chat.avatar" size="small"></el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ chat.title || '新的英语对话' }}</div>
                <div class="contact-difficulty" v-if="chat.difficulty">
                  <el-tag size="mini" :type="getDifficultyType(chat.difficulty)">
                    {{ getDifficultyLabel(chat.difficulty) }}
                  </el-tag>
                </div>
              </div>
              <div class="contact-meta">
                <span class="time">{{ chat.time }}</span>
              </div>
            </div>
            <div class="contact-actions">
              <el-tooltip content="修改设置" placement="top" :open-delay="300">
                <i class="el-icon-setting action-icon edit-icon" @click.stop="openSettingsDialog(chat.id)"></i>
              </el-tooltip>
              <el-tooltip content="删除对话" placement="top" :open-delay="300">
                <i class="el-icon-delete action-icon delete-icon" @click.stop="deleteChat(chat.id)"></i>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-content">
        <div v-if="activeContact !== null" class="chat-header">
          <h3>{{ getActiveChatTitle() }}</h3>
          <div class="chat-options" v-if="getActiveChatKeywords()">
            <el-tag v-for="keyword in getActiveChatKeywords()" :key="keyword" size="small" class="keyword-tag">
              {{ keyword }}
            </el-tag>
          </div>
        </div>
        <div v-else class="chat-header">
          <h3>欢迎使用英语对话助手</h3>
        </div>
          <div class="messages-container" ref="messagesContainer">
          <div v-if="activeContact !== null" class="messages">
            <div 
              v-for="(message, index) in messages" 
              :key="index"
              class="message"
              :class="{ 'own-message': message.own }"
            >
              <el-avatar 
                :src="message.own ? userImageUrl : getActiveChatAvatar()" 
                size="small"
              ></el-avatar>              <div class="message-content">
                <div class="message-text" v-html="formatMessageText(message.text)"></div>
                <div class="message-time">{{ message.time }}</div>
                <!-- 重新生成按钮，只对AI回复显示 -->
                <div v-if="!message.own && message.messageId" class="message-actions">
                  <el-button 
                    size="mini" 
                    type="text" 
                    @click="regenerateMessage(message, index)"
                    class="regenerate-btn"
                    :loading="message.regenerating"
                  >
                    <i class="el-icon-refresh"></i> 重新生成
                  </el-button>
                </div>
              </div>
            </div>
            <!-- 当选中了对话但没有消息时的提示 -->
            <div v-if="messages.length === 0" class="no-messages-hint">
              <p>这是一个新的英语对话，开始你的第一句话吧！</p>
            </div>
          </div>
          <div v-else class="no-chat-selected">
            <img src="https://cdn.iconscout.com/icon/free/png-256/free-chat-2639493-2187526.png" alt="Chat Icon" class="chat-icon"/>
            <p>创建一个新的英语对话，提高你的英语交流能力</p>
            <el-button type="primary" @click="openNewChatDialog" class="new-chat-big-btn">
              <i class="el-icon-plus"></i> 开始新对话
            </el-button>
          </div>
        </div>
        
        <div v-if="activeContact !== null" class="chat-input">
          <div class="input-actions">
            <i class="el-icon-mic" title="语音输入"></i>
            <i class="el-icon-refresh" title="清空输入"></i>
          </div>
          <div class="input-field">
            <textarea 
              v-model="newMessage" 
              placeholder="用英语输入你想说的..." 
              @keyup.enter.ctrl="sendMessage"
            ></textarea>
            <small class="input-tip">按Ctrl+Enter发送</small>
          </div>
          <el-button type="primary" @click="sendMessage" :disabled="!newMessage.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 新建对话设置对话框 -->
    <el-dialog
      title="开始新的英语对话"
      v-model:modelValue="newChatDialogVisible"
      :width="'500px'"
      :modal="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      custom-class="new-chat-dialog"
      center="true"
    >
      <div class="dialog-content">
        <el-form label-position="top" :model="newChatForm">
          <el-form-item label="对话标题">
            <el-input v-model="newChatForm.title" placeholder="输入对话标题"></el-input>
          </el-form-item>
          <el-form-item label="难度级别">
            <el-select v-model="newChatForm.difficulty" placeholder="选择难度级别" style="width: 100%">
              <el-option v-for="option in difficultyOptions" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>          <el-form-item label="主题/关键词">
            <el-select
              v-model="newChatForm.keywords"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="选择或输入主题关键词"
              style="width: 100%"
              :collapse-tags="false"
              :sortable="false"
            >
              <el-option
                v-for="item in keywordOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初始消息 (可选)">
            <el-input 
              type="textarea" 
              v-model="newChatForm.initialMessage" 
              placeholder="输入开场白 (例如: Hello, how are you today?)"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="newChatDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createNewChat" :loading="creatingChat">创建</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 修改设置对话框 -->
    <el-dialog
      title="修改对话设置"
      v-model:modelValue="settingsDialogVisible"
      :width="'500px'"
      :modal="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      custom-class="settings-dialog"
      center="true"
    >
      <div class="dialog-content">
        <el-form label-position="top" :model="chatSettingsForm">
          <el-form-item label="对话标题">
            <el-input v-model="chatSettingsForm.title" placeholder="输入对话标题"></el-input>
          </el-form-item>
          <el-form-item label="难度级别">
            <el-select v-model="chatSettingsForm.difficulty" placeholder="选择难度级别" style="width: 100%">
              <el-option v-for="option in difficultyOptions" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>          <el-form-item label="主题/关键词">
            <el-select
              v-model="chatSettingsForm.keywords"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="选择或输入主题关键词"
              style="width: 100%"
              :collapse-tags="false"
              :sortable="false"
            >
              <el-option
                v-for="item in keywordOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateChatSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import request from "@/utils/request.js"; 

import "@/css/chat.css"; // 新增这行来引入CSS文件
export default {
  name: "EnglishChat",
  components: {
    Header
  },
  data() {
    return {
      chats: [],
      activeContact: null,
      messages: [],
      newMessage: "",
      userImageUrl: this.$store.getters.userImageUrl,
      botAvatar: "https://img.icons8.com/color/48/000000/english--v1.png", // 英语助手头像
      newChatDialogVisible: false,
      settingsDialogVisible: false,
      creatingChat: false,
      loading: false,
      newChatForm: {
        title: "英语对话",
        difficulty: "medium",
        keywords: [],
        initialMessage: "Hello! Let's talk"
      },
      chatSettingsForm: {
        id: null,
        title: "",
        difficulty: "",
        keywords: []
      },
      difficultyOptions: [
        { value: "easy", label: "简单" },
        { value: "medium", label: "中等" },
        { value: "hard", label: "困难" }
      ],
      keywordOptions: [
        { value: "旅行", label: "旅行" },
        { value: "食物", label: "食物" },
        { value: "工作", label: "工作" },
        { value: "学习", label: "学习" },
        { value: "电影", label: "电影" },
        { value: "音乐", label: "音乐" },
        { value: "体育", label: "体育" },
        { value: "科技", label: "科技" },
        { value: "天气", label: "天气" },
        { value: "购物", label: "购物" }
      ],
      currentEditingChatId: null
    };
  },  created() {
    // 从后端获取聊天记录
    this.fetchChats();
    // 获取英语对话设置选项
    this.fetchChatOptions();
  },
  methods: {    // 获取聊天列表
    fetchChats() {
      this.loading = true;
      // 使用request模块获取聊天记录
      request.get('/model-chats', { params: { type: 'english' } })
        .then(res => {
          console.log('获取英语对话记录:', JSON.stringify(res, null, 2));
          // 假设API返回数据格式为数组，每个元素包含id, title, lastMessage等字段
          if (res && res.code==0 && Array.isArray(res.data)) {
            // 处理返回的数据，确保每个聊天记录都有正确的日期对象
            this.chats = res.data.map(chat => ({
              id: chat.chatId,  // 将后端的 chatId 映射为前端的 id
              title: chat.title || "新的英语对话",
              avatar: this.botAvatar, // 设置默认头像
              time: this.formatMessageTime(chat.updatedAt), // 格式化时间显示
              createdAt: new Date(chat.createdAt || Date.now()), // 确保createdAt是Date对象
              updatedAt: new Date(chat.updatedAt || Date.now()), // 确保updatedAt是Date对象
              difficulty: chat.difficulty || "medium", // 对话难度
              keywords: chat.keywords ? chat.keywords.split(',') : [] // 关键词/主题
            }));
            // 按最近访问时间排序
            this.sortChatsByTime();
            
            // 检查是否需要自动选择返回的对话
            this.checkAndSelectReturnChat();
          }
        })
        .catch(error => {
          console.error('获取英语对话记录失败:', error);
          this.$message.error('获取英语对话记录失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取英语对话设置选项
    fetchChatOptions() {
      request.get('/english-chat/options')
        .then(res => {
          if (res && res.code == 0 && res.data) {
            // 如果后端返回了预设选项，则更新本地选项
            if (res.data.difficulties && res.data.difficulties.length > 0) {
              this.difficultyOptions = res.data.difficulties.map(diff => ({
                value: diff.value,
                label: diff.label
              }));
            }
            
            if (res.data.topics && res.data.topics.length > 0) {
              this.keywordOptions = res.data.topics.map(topic => ({
                value: topic.value || topic.name,
                label: topic.label || topic.name
              }));
            }
          }
        })
        .catch(error => {
          console.error('获取英语对话选项失败:', error);
        });
    },    sortChatsByTime() {
      this.chats.sort((a, b) => b.updatedAt - a.updatedAt);
    },
      // 检查并选择返回的对话
    checkAndSelectReturnChat() {
      const returnChatId = this.$route.query.chatId;
      if (returnChatId) {
        console.log('检查返回的聊天ID:', returnChatId, '类型:', typeof returnChatId);
        console.log('当前聊天列表:', this.chats.map(chat => ({ id: chat.id, title: chat.title, idType: typeof chat.id })));
        
        // 尝试数字和字符串两种匹配方式
        const chatExists = this.chats.find(chat => 
          chat.id == returnChatId || 
          chat.id === returnChatId || 
          chat.id === parseInt(returnChatId) || 
          chat.id === returnChatId.toString()
        );
        
        if (chatExists) {
          console.log('找到对应的聊天记录:', chatExists);
          this.selectContact(chatExists.id); // 使用找到的聊天记录的ID
          // 清除URL中的chatId参数，避免刷新页面时重复选择
          this.$router.replace({ path: '/english-chat' });
        } else {
          console.log('未找到对应的聊天记录，returnChatId:', returnChatId);
        }
      }
    },
    
    openNewChatDialog() {
      // 重置表单
      this.newChatForm = {
        title: "英语对话",
        difficulty: "medium",
        keywords: [],
        initialMessage: "Hello! Let's talk"
      };
      this.newChatDialogVisible = true;
    },
    createNewChat() {
      this.creatingChat = true;
      
      // 准备请求体
      const requestData = {
        title: this.newChatForm.title,
        difficulty: this.newChatForm.difficulty,
        keywords: this.newChatForm.keywords.join(','),
        initialMessage: this.newChatForm.initialMessage
      };
      
      // 创建新的英语对话会话
      request.post('/english-chat', requestData)
        .then(res => {
          console.log('创建新的英语对话,格式化的数据:', JSON.stringify(res, null, 2));
          if (res && res.code == 0 && res.data) {
            const chat = res.data;
            const newChat = {
              id: chat.chatId,
              title: chat.title || "新的英语对话",
              avatar: this.botAvatar,
              time: this.formatMessageTime(chat.updatedAt),
              createdAt: new Date(chat.createdAt || Date.now()),
              updatedAt: new Date(chat.updatedAt || Date.now()),
              difficulty: chat.difficulty || this.newChatForm.difficulty,
              keywords: chat.keywords ? chat.keywords.split(',') : this.newChatForm.keywords
            };            this.chats.unshift(newChat);
            
            this.$message.success('创建成功');
            this.newChatDialogVisible = false;
            
            console.log('新建对话成功，准备选择对话:', newChat.id); // 调试日志
            
            // 确保对话框关闭和DOM更新后再选择对话
            this.$nextTick(() => {
              // 延迟一下确保后端处理完成
              setTimeout(() => {
                this.selectContact(newChat.id);
              }, 200);
            });
          } else {
            this.$message.error('创建失败: ' + (res.message || '未知错误'));
          }
        })
        .catch(error => {
          console.error('创建新英语对话失败:', error);
          this.$message.error('创建新英语对话失败，请稍后重试');
        })
        .finally(() => {
          this.creatingChat = false;
        });
    },    openSettingsDialog(chatId) {
      // 确保 chatId 是有效的
      if (chatId === undefined || chatId === null) {
        console.error('打开设置对话框失败: 无效的聊天ID', chatId);
        this.$message.error('操作失败: 无效的聊天');
        return;
      }
      
      const chat = this.chats.find(c => c.id === chatId);
      if (chat) {
        this.currentEditingChatId = chatId;
        this.chatSettingsForm = {
          id: chatId,
          title: chat.title,
          difficulty: chat.difficulty || "medium",
          keywords: Array.isArray(chat.keywords) ? [...chat.keywords] : []
        };
        
        this.settingsDialogVisible = true;
      }
    },    updateChatSettings() {
      if (!this.chatSettingsForm.title.trim()) {
        this.$message.error('标题不能为空');
        return;
      }
      
      // 确保 currentEditingChatId 是有效的
      if (this.currentEditingChatId === undefined || this.currentEditingChatId === null) {
        console.error('更新设置失败: 无效的聊天ID', this.currentEditingChatId);
        this.$message.error('更新设置失败: 无效的聊天ID');
        return;
      }
      
      const requestData = {
        title: this.chatSettingsForm.title,
        difficulty: this.chatSettingsForm.difficulty,
        keywords: this.chatSettingsForm.keywords.join(',')
      };
      
      request.put(`/model-chats/${this.currentEditingChatId}`, requestData)
        .then(res => {
          if (res && res.code == 0) {
            const chatIndex = this.chats.findIndex(chat => chat.id === this.currentEditingChatId);
            if (chatIndex !== -1) {
              this.chats[chatIndex].title = this.chatSettingsForm.title;
              this.chats[chatIndex].difficulty = this.chatSettingsForm.difficulty;
              this.chats[chatIndex].keywords = [...this.chatSettingsForm.keywords];
              
              this.$message.success('设置已更新');
              this.settingsDialogVisible = false;
              this.currentEditingChatId = null;
            }
          } else {
            this.$message.error('更新设置失败: ' + (res.message || '未知错误'));
          }
        })
        .catch(error => {
          console.error('更新对话设置失败:', error);
          this.$message.error('更新设置失败，请稍后重试');
        });
    },    selectContact(id) {
      // 确保 id 是有效的，不是 undefined 或 null
      if (id === undefined || id === null) {
        console.error('聊天ID无效:', id);
        this.$message.error('选择的聊天无效');
        return;
      }
      
      console.log('选择对话:', id, '类型:', typeof id); // 调试日志
      this.activeContact = id;
      
      // 找到当前选择的聊天，使用宽松比较来处理类型转换
      const chatIndex = this.chats.findIndex(chat => 
        chat.id == id || 
        chat.id === id || 
        chat.id === parseInt(id) || 
        chat.id === id.toString()
      );
      
      if (chatIndex === -1) {
        console.error('未找到对应的聊天记录:', id);
        console.log('当前聊天列表:', this.chats.map(chat => ({ id: chat.id, idType: typeof chat.id })));
        this.$message.error('未找到对应的聊天记录');
        return;
      }
      
      console.log('成功找到聊天记录，索引:', chatIndex, '聊天标题:', this.chats[chatIndex].title); // 调试日志
      
      // 加载消息（对新对话来说，这会返回空数组，这是正常的）
      this.loadMessages(id);
      
      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },sendMessage() {
      if (!this.newMessage.trim()) return;
      
      // 确保 activeContact 是有效的
      if (this.activeContact === undefined || this.activeContact === null) {
        console.error('发送消息失败: 无效的聊天ID', this.activeContact);
        this.$message.error('发送消息失败: 请先选择聊天');
        return;
      }
      
      // 添加新消息到本地显示
      this.messages.push({
        text: this.newMessage,
        time: this.getCurrentTime(),
        own: true
      });
      
      const sentMessage = this.newMessage;
      
      // 更新最后一条消息并更新访问时间（因为有新输入）
      const chatIndex = this.chats.findIndex(chat => chat.id === this.activeContact);
      if (chatIndex >= 0) {
        this.chats[chatIndex].time = "刚刚";
        
        // 只在发送消息时更新访问时间
        this.chats[chatIndex].updatedAt = new Date();
        
        this.sortChatsByTime();
      }
      
      // 清空输入
      this.newMessage = "";
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      // 显示正在输入提示
      this.showTypingIndicator();
      
      // 发送消息到后端并获取回复
      request.post(
        `/model-chats/${this.activeContact}/messages`,
        { content: sentMessage },
        { timeout: 90000 } // 单独设置超时时间为90秒
      )
      .then(res => {
        console.log('格式化回答:', JSON.stringify(res, null, 2));
        // 移除typing指示器
        this.messages = this.messages.filter(m => !m.isTyping);

        // 处理data里的数据，假设res.data为回复内容
        if (res && res.code==0 && res.data) {
          this.messages.push({
            chatId: res.data.chatId,
            messageId: res.data.messageId,
            own: res.data.isUser,  // 映射isUser到own以匹配前端模板
            text: res.data.text,
            time: this.formatMessageTime(res.data.createdTime)
          });
        } else {
          this.messages.push({
            text: '抱歉，英语助手暂时无法回应',
            time: this.getCurrentTime(),
            own: false
          });
        }
        
        // 更新聊天列表中的最后一条消息
        const chatIndex = this.chats.findIndex(chat => chat.id === this.activeContact);
        if (chatIndex >= 0) {
          this.chats[chatIndex].time = "刚刚";
          this.sortChatsByTime();
        }
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      })
      .catch(error => {
        console.error('发送消息失败:', error);
        this.$message.error('发送消息失败，请稍后重试');
        
        // 移除typing指示器
        this.messages = this.messages.filter(m => !m.isTyping);
      });
    },    deleteChat(chatId) {
      // 确保 chatId 是有效的
      if (chatId === undefined || chatId === null) {
        console.error('删除聊天失败: 无效的聊天ID', chatId);
        this.$message.error('删除失败: 无效的聊天');
        return;
      }
      
      this.$confirm('确认删除此英语对话记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用request删除聊天
        request.delete(`/model-chats/${chatId}`)
          .then(() => {
            // 删除聊天
            const index = this.chats.findIndex(chat => chat.id === chatId);
            if (index !== -1) {
              this.chats.splice(index, 1);
              
              // 如果删除的是当前活动聊天，重置活动聊天
              if (this.activeContact === chatId) {
                this.activeContact = null;
                this.messages = [];
              }
            }
            
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
          .catch(error => {
            console.error('删除对话记录错误:', error);
            this.$message.error('删除对话记录失败，请稍后重试');
          });
      }).catch(() => {
        // 用户取消删除
      });
    },    showTypingIndicator() {
      this.messages.push({
        text: "正在输入...",
        time: this.getCurrentTime(),
        own: false,
        isTyping: true
      });
    },      loadMessages(chatId) {
      // 确保 chatId 是有效的，不是 undefined 或 null
      if (chatId === undefined || chatId === null) {
        console.error('加载消息失败: 无效的聊天ID', chatId);
        this.$message.error('加载消息失败: 无效的聊天ID');
        return;
      }
      
      console.log('加载消息，聊天ID:', chatId); // 调试日志
      
      // 使用request获取消息记录
      request.get(`/model-chats/${chatId}/messages`)
        .then(res => {
          if (res && res.code==0 && Array.isArray(res.data)) {
            console.log('获取消息格式化的数据:', JSON.stringify(res, null, 2));
            this.messages = res.data.map(msg => ({
              chatId: msg.chatId,
              messageId: msg.messageId,
              own: msg.isUser,  // 映射isUser到own以匹配前端模板
              text: msg.text,
              time: this.formatMessageTime(msg.createdTime)
            }));
            console.log('消息加载完成，共', this.messages.length, '条消息');
          } else {
            // 处理响应格式不符合预期的情况，对于新对话这是正常的
            this.messages = [];
            console.log('暂无消息记录，这可能是一个新对话');
          }
        })
        .catch(error => {
          console.error('获取消息记录失败:', error);
          // 对于新创建的对话，可能还没有消息记录，这是正常情况
          if (error.response && error.response.status === 404) {
            console.log('对话暂无消息记录，这是新对话的正常状态');
            this.messages = [];
          } else {
            this.$message.error('获取消息记录失败，请稍后重试');
            this.messages = [];
          }
        });
    },
    getDifficultyType(difficulty) {
      const types = {
        easy: 'success',
        medium: 'warning',
        hard: 'danger'
      };
      return types[difficulty] || 'info';
    },
    getDifficultyLabel(difficulty) {
      const labels = {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      };
      return labels[difficulty] || '未知';
    },
    getActiveChatTitle() {
      const chat = this.chats.find(c => c.id === this.activeContact);
      return chat ? chat.title : '英语对话';
    },
    getActiveChatAvatar() {
      const chat = this.chats.find(c => c.id === this.activeContact);
      return chat ? chat.avatar : this.botAvatar;
    },
    getActiveChatKeywords() {
      const chat = this.chats.find(c => c.id === this.activeContact);
      return chat && chat.keywords ? chat.keywords : [];
    },
    formatMessageTime(timestamp) {
      if (!timestamp) return this.getCurrentTime();
      
      const date = new Date(timestamp);
      const now = new Date();
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      // 如果是今天的消息，只显示时间
      if (date.toDateString() === now.toDateString()) {
        return `${hours}:${minutes}`;
      }
      
      // 如果是昨天的消息
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${hours}:${minutes}`;
      }
      
      // 其他情况显示日期
      return `${date.getMonth() + 1}-${date.getDate()} ${hours}:${minutes}`;
    },    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },
        regenerateMessage(message, messageIndex) {
      // 获取用户的原始消息（AI回复的前一条消息）
      const userMessage = this.messages[messageIndex - 1];
      if (!userMessage || userMessage.own !== true) {
        this.$message.error('无法找到对应的用户消息');
        return;
      }

      // 设置重新生成状态
      message.regenerating = true;

      // 发送新的重新生成请求到 /regenerate 路径
      request.post(
        `/model-chats/${this.activeContact}/messages/${message.messageId}/regenerate`,
        { content: userMessage.text },
        { timeout: 90000 }
      )
        .then(res => {
          console.log('重新生成英语对话回复:', JSON.stringify(res, null, 2));
          if (res && res.code == 0 && res.data) {
            // 更新消息内容
            this.messages[messageIndex] = {
              chatId: res.data.chatId,
              messageId: res.data.messageId,
              own: res.data.isUser,
              text: res.data.text,
              time: this.formatMessageTime(res.data.createdTime),
              regenerating: false
            };
            this.$message.success('重新生成成功');
          } else {
            message.regenerating = false;
            this.$message.error('重新生成失败，请稍后重试');
          }
        })
        .catch(error => {
          console.error('重新生成英语对话消息失败:', error);
          message.regenerating = false;
          this.$message.error('重新生成失败，请稍后重试');
        });    },
    getCurrentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },    // 格式化消息文本，处理think部分、括号提示文本并为英文单词添加点击功能
    formatMessageText(text) {
      if (!text) return '';
      
      // 首先处理并移除think部分
      let processedText = this.removeThinkContent(text);
      
      // 处理括号中的提示文本，如: *(Remember, you can tell me about your day!)*
      // 移除外层括号和星号，并用不同颜色显示
      processedText = processedText.replace(/\*?\(([^)]+)\)\*?/g, (match, content) => {
        return `<span class="hint-text">${content}</span>`;
      });      // 英文单词的正则表达式 - 匹配连续的英文字母（至少2个字符）
      // 但不要匹配已经被span标签包围的内容
      const wordRegex = /\b[a-zA-Z]{2,}\b(?![^<]*>)/g;
        return processedText.replace(wordRegex, (match) => {
        // 排除一些常见的非实词（可根据需要扩展）
        const skipWords = ['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'my', 'your', 'his', 'her', 'its', 'our', 'their'];
        
        if (skipWords.includes(match.toLowerCase())) {
          return match; // 保持原样，不添加点击功能
        }
        
        return `<span class="clickable-word" 
                      data-word="${match.toLowerCase()}" 
                      onclick="if(window.handleWordClick) window.handleWordClick('${match.toLowerCase()}')">${match}</span>`;
      });
    },
    
    // 移除think内容的方法
    removeThinkContent(text) {
      if (!text) return '';
      
      // 匹配并移除 <think>...</think> 标签及其内容
      const thinkRegex = /<think>[\s\S]*?<\/think>/gi;
      let cleanedText = text.replace(thinkRegex, '');
      
      // 匹配并移除 think> 开头的内容（处理不完整的think标签）
      const incompleteThinkRegex = /think>[\s\S]*?(?=\n\n|\n[A-Z]|$)/gi;
      cleanedText = cleanedText.replace(incompleteThinkRegex, '');
      
      // 清理多余的空白行
      cleanedText = cleanedText.replace(/\n\s*\n\s*\n/g, '\n\n');
      
      return cleanedText.trim();
    },    handleWordClick(word) {
      if (!word) return;
      
      console.log('点击单词:', word); // 调试日志
      
      // 跳转到单词详情页面，并传递来源页面信息和当前对话ID
      this.$router.push({
        path: `/word/${encodeURIComponent(word)}`,
        query: { 
          from: '/english-chat',
          chatId: this.activeContact  // 保存当前对话ID
        }
      }).catch(err => {
        console.error('路由跳转失败:', err);
        this.$message.error('跳转单词详情页面失败');
      });
    }
  },  mounted() {
    // 在组件挂载后设置全局的单词点击处理函数
    window.handleWordClick = (word) => {
      this.handleWordClick(word);
    };
    
    // 添加事件委托处理点击事件
    this.handleContainerClick = (event) => {
      const target = event.target;
      if (target && target.classList.contains('clickable-word')) {
        const word = target.getAttribute('data-word');
        if (word) {
          event.preventDefault();
          event.stopPropagation();
          this.handleWordClick(word);
        }
      }
    };
    
    this.$nextTick(() => {
      const messagesContainer = this.$refs.messagesContainer;
      if (messagesContainer) {
        messagesContainer.addEventListener('click', this.handleContainerClick);
      }
    });
  },
    beforeUnmount() {
    // 组件销毁前清理全局函数
    delete window.handleWordClick;
    
    // 清理事件监听器
    const messagesContainer = this.$refs.messagesContainer;
    if (messagesContainer) {
      messagesContainer.removeEventListener('click', this.handleContainerClick);
    }
  }
};
</script>

<style scoped>
/* 组件特有样式，其余样式已在外部 chat.css 中定义 */

/* 确保消息容器的相对定位 */
.messages-container {
  position: relative !important;
}

/* 新对话无消息时的提示样式 */
.no-messages-hint {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.no-messages-hint p {
  margin: 0;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}
</style>
